package com.sky.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired(required = false)
    StringRedisTemplate redisTemplate;


    /**
     * 添加套餐
     *
     * @param dto
     * @return
     */
    @Override
    public Result addSetmeal(SetmealDTO dto) {
        //处理参数
        if (dto.getCategoryId() == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //dto不能直接添加到表因为属性值不完全一样所以需要封装到实体类
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto,setmeal);
        //调用dao添加,并在mapper用AOP添加剩余参数
        setmealMapper.addSetmeal(setmeal);

        //还需要获取生成返回的套餐id
        Long id = setmeal.getId();

        //套餐添加完成后还需要添加套餐菜品关联表//批量保存套餐和菜品的关联关系,因为都是多条数据
            //获取关联表数据
        List<SetmealDish> setmealDishesList = dto.getSetmealDishes();
        //循环插入id到setmealDishesList中补全数据
        for (SetmealDish setmealDish : setmealDishesList) {
            setmealDish.setSetmealId(id);
        }
        //dao保存套餐和菜品关系表
        setmealDishMapper.add(setmealDishesList);

        return Result.success();
    }

    /**
     * 分页条件查询套餐
     *
     * @param dto
     * @return
     */
    @Override
    public Result page(SetmealPageQueryDTO dto) {
        //添加分页默认值
        if (dto.getPage() == null){
            dto.setPage(1);
        }
        if (dto.getPageSize() == null){
            dto.setPageSize(10);
        }
        //开启分页
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<SetmealVO> pageVo = setmealMapper.page(dto);

        PageResult pageResult = new PageResult();
        pageResult.setTotal(pageVo.getTotal());
        pageResult.setRecords(pageVo.getResult());

        return Result.success(pageResult);
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result delete(List<Long> ids) {
        //判空
        if (ids == null || ids.size() == 0){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }

        //起售中套餐不能删除,查询要删除的套餐状态
        for (Long id : ids) {
            //根据id查询套餐
            Setmeal setmeal = setmealMapper.getByid(id);
            //判断套餐是否启用
            if (setmeal.getStatus() == StatusConstant.ENABLE){
                //起售中套餐不能删除
                return Result.error(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        for (Long setmealId : ids) {
            //套餐未启用,删除套餐数据
            setmealMapper.delete(setmealId);
            //删除关联表setmeal_dis表数据
            setmealDishMapper.deleteBySetmealId(setmealId);
        }
        return Result.success();
    }

    /**
     * 根据id查询套餐和关联的菜品数据
     *
     * @param id
     * @return
     */
    @Override
    public Result getById(Long id) {
        //判空
        if (id == null){
            return Result.error(MessageConstant.ID_EXISTS_FOUND);
        }
        //dao查询
        SetmealVO setmealVO = new SetmealVO();
        Setmeal setmeal = setmealMapper.getByid(id);
        BeanUtils.copyProperties(setmeal,setmealVO);

        //补全数据到dto查询setmeal_dish
        List<SetmealDish> setmealDishList = setmealDishMapper.getBYSetmealId(id);

        setmealVO.setSetmealDishes(setmealDishList);


        //返回数据
        return Result.success(setmealVO);
    }


    /**
     * 修改套餐
     *
     * @param setmealDTO
     */
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //1、修改套餐表，执行update
        setmealMapper.update(setmeal);

        //套餐id
        Long setmealId = setmealDTO.getId();

        //2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        setmealDishMapper.deleteBySetmealId(setmealId);

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        //3、重新插入套餐和菜品的关联关系，操作setmeal_dish表，执行insert
        setmealDishMapper.add(setmealDishes);
    }



    /**
     * 套餐起售、停售
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        //起售套餐时，判断套餐内是否有停售菜品，有停售菜品提示"套餐内包含未启售菜品，无法启售"
        if(status == StatusConstant.ENABLE){
            //select a.* from dish a left join setmeal_dish b on a.id = b.dish_id where b.setmeal_id = ?
            List<Dish> dishList = dishMapper.getBySetmealId(id);
            if(dishList != null && dishList.size() > 0){
                dishList.forEach(dish -> {
                    if(StatusConstant.DISABLE == dish.getStatus()){
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }

        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);
    }


    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {

        //否则就是没有数据,查询mysql,写入数据到redis中
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }

}
